package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Permission;
import cn.wolfcode.mapper.PermissionMapper;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.util.RequiredPermission;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.util.*;

/**
 * Created by wolfcode-lanxw
 */
@Service
public class PermissionServiceImpl implements IPermissionService {

    @Autowired
    private RequestMappingHandlerMapping rmhm;
    @Autowired
    private PermissionMapper permissionMapper;


    @Override
    public List<Permission> selectALL() {
        return  permissionMapper.selectAll();
    }

    @Override
    public PageInfo<Permission> list(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
        List<Permission> list = permissionMapper.list(qo);
        return new PageInfo<>(list);
    }

    @Override
    public void reload() {
        //1.一次性的把所有的权限信息查出来.
        List<Permission> permissions = permissionMapper.selectAll();
        Set<String> expressionSet = new HashSet<>();
        for(Permission p:permissions){
            expressionSet.add(p.getExpression());
        }

        //获取到所有贴了RequiredPermission注解，取出注解上的name和expression，
        // 封装成Permission，保存到数据库中
        //HandlerMethod代表每一个控制的方法引用
        Map<RequestMappingInfo, HandlerMethod> handlerMethods = rmhm.getHandlerMethods();
        Collection<HandlerMethod> values = handlerMethods.values();
        for(HandlerMethod method:values){
            RequiredPermission methodAnnotation = method.getMethodAnnotation(RequiredPermission.class);
            if(methodAnnotation!=null){
                String expression = methodAnnotation.expression();

                if(!expressionSet.contains(expression)){
                    //说明在数据库集合中已经包含该表达式的权限了
                    //说明方法上贴了注解
                    Permission p = new Permission();
                    p.setName(methodAnnotation.name());
                    p.setExpression(expression);
                    permissionMapper.insert(p);
                }else {
                    expressionSet.remove(expression);
                }
            }
        }
        for(String expression:expressionSet){
            permissionMapper.deleteByExpression(expression);
        }
    }

    @Override
    public List selectByroleId(Long roleId) {
        return permissionMapper.selectByroleId(roleId);
    }

    @Override
    public List<Permission> selectByPermission(Long empId) {
        return  permissionMapper.selectByPermission(empId);
    }
}
